﻿using Dapr;
using Dapr.Actors;
using Dapr.Actors.Client;
using Dapr.Client;
using Microsoft.AspNetCore.Mvc;
using MyActor.Interfaces;
using MyActorService.Models;
using System.Diagnostics;

namespace MyActorService.Controllers
{
    public class StateController : Controller
    {
        private readonly ILogger<StateController> _logger;
        private readonly DaprClient daprclient;
        public StateController(ILogger<StateController> logger, DaprClient daprClient)
        {
            _logger = logger;
            daprclient = daprClient;
        }
        /// <summary>
        /// daprclient写入redis
        /// </summary>
        /// <returns></returns>
        public async Task Save()
        {
            //using var daprclient = new DaprClientBuilder().UseGrpcEndpoint("http://localhost:50003").Build();

            var acity = new OrderItem() { Product = new Product() { Id = "33" }, Quantity = 4 };
            var bcity = new OrderItem() { Product = new Product() { Id = "55" }, Quantity = 5 };
            await daprclient.SaveStateAsync("statestore", nameof(acity), acity);
            await daprclient.SaveStateAsync("statestore", nameof(bcity), bcity);
            OrderItem re = await daprclient.GetStateAsync<OrderItem>("statestore", nameof(bcity));
            _logger.LogInformation($"Save返回：{System.Text.Json.JsonSerializer.Serialize(re)}");
        }

        /// <summary>
        /// daprclient查询redis
        /// </summary>
        /// <returns></returns>
        public async Task<OrderItem> Get()
        {
            var bcity = new OrderItem() { };
            OrderItem item = await daprclient.GetStateAsync<OrderItem>("statestore", "bcity");
            var (item2, etag) = await daprclient.GetStateAndETagAsync<OrderItem>("statestore", nameof(bcity));
            _logger.LogInformation($"Get返回,etag={etag},item={System.Text.Json.JsonSerializer.Serialize(item2)}");
            return item;
        }
        /// <summary>
        /// daprclient 删除或更新检索到的键/值数据
        /// </summary>
        /// <param name="updatedForecast"></param>
        /// <param name="currentForecast"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task Update()
        { 
            var weatherEntry = await daprclient.GetStateEntryAsync<OrderItem>("statestore", "bcity");
            weatherEntry.Value = new() { Product = new Product() { Id = "33332", Quantity = 3332 }, Quantity = 333332 };
            await weatherEntry.SaveAsync();
            _logger.LogInformation($"Update返回, item={System.Text.Json.JsonSerializer.Serialize(weatherEntry)}");
        }


        #region MyRegion
        /// <summary>
        /// 不需要引用 DaprClient 对象
        /// </summary>
        /// <param name="forecast"></param>
        /// <returns></returns> 
        [HttpGet("{city=bcity}")]
        public ActionResult<OrderItem> City([FromState("statestore", "city")] StateEntry<OrderItem> forecast)
        {
            _logger.LogInformation($"City返回, item={System.Text.Json.JsonSerializer.Serialize(forecast)}");
            if (forecast?.Value == null)
            {
                return NotFound();
            }
            return forecast.Value;
        }

        public IEnumerable<WeatherForecast> GetList()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
        private static readonly string[] Summaries = new[]
        {
         "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        #endregion




    }
}